package com.boot.realm;

import com.boot.token.MyToken;
import com.boot.utils.JwtUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

@Component
public class MyRealm extends AuthorizingRealm {

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof MyToken;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        /*
            PrincipalCollection 身份的集合
            一个主体可以有多个身份，但是只有一个主身份
         */
        // 获取主体的主身份
        //String principal = (String) principals.getPrimaryPrincipal();

        // 模拟根据用户的身份信息 从数据库中查询其角色信息
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("admin");
        simpleAuthorizationInfo.addRole("user");

        // 模拟从数据库查询权限信息，赋值给某个对象
        simpleAuthorizationInfo.addStringPermission("user:*:01");
        simpleAuthorizationInfo.addStringPermission("product:create:01");

        return simpleAuthorizationInfo;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        // 从 token 中获取用户输入的身份凭证
        MyToken myToken = (MyToken) token;
        String userName = (String)myToken.getPrincipal();

        // 模拟从数据库查询出的密码
        String password = "123456";

        //这里如果没有报错 说明验证通过 如果报错则验证失败,不会继续执行
        JwtUtils.verifyToken(myToken.getToken());
        return new SimpleAuthenticationInfo(userName, password, this.getName());
    }
}
